{
 "cells": [
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "# default_exp data.mixed"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# Mixed data\n",
    "\n",
    "> DataLoader than can take data from multiple dataloaders with different types of data"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "#export\n",
    "from tsai.imports import *"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "# export\n",
    "# This implementation of a mixed dataloader is based on a great implementation created by Zach Mueller in this fastai thread:\n",
    "# https://forums.fast.ai/t/combining-tabular-images-in-fastai2-and-should-work-with-almost-any-other-type/73197\n",
    "\n",
    "from packaging import version\n",
    "from fastai.data.load import _FakeLoader\n",
    "from torch.utils.data.dataloader import _MultiProcessingDataLoaderIter, _SingleProcessDataLoaderIter, _DatasetKind\n",
    "_loaders = (_MultiProcessingDataLoaderIter, _SingleProcessDataLoaderIter)\n",
    "\n",
    "\n",
    "class MixedDataLoader():\n",
    "    def __init__(self, *loaders, path='.', shuffle=False, device=None, bs=None):\n",
    "        \"Accepts any number of `DataLoader` and a device\"\n",
    "        self.path = path\n",
    "        device = ifnone(device, default_device())\n",
    "        self.device = device\n",
    "        self.c = None\n",
    "        self.d = None\n",
    "        self.bs = ifnone(bs, min([dl.bs for dl in loaders]))\n",
    "        for i, dl in enumerate(loaders):  # ensure all dls have the same bs\n",
    "            if hasattr(dl, 'vars'):\n",
    "                self.vars = dl.vars\n",
    "            if hasattr(dl, 'len'):\n",
    "                self.len = dl.len\n",
    "            if hasattr(dl, 'split_idxs'):\n",
    "                self.split_idxs = dl.split_idxs\n",
    "            dl.bs = self.bs\n",
    "            dl.shuffle_fn = self.shuffle_fn\n",
    "            if self.c is None and hasattr(dl, \"c\"):\n",
    "                self.c = dl.c\n",
    "            if self.d is None and hasattr(dl, \"d\"):\n",
    "                self.d = dl.d\n",
    "            if i == 0:\n",
    "                self.dataset = dl.dataset\n",
    "            dl.to(device=device)\n",
    "        self.shuffle = shuffle\n",
    "        if not self.shuffle:\n",
    "            self.rng = np.arange(len(self.dataset)).tolist()\n",
    "        self.loaders = loaders\n",
    "        self.count = 0\n",
    "        self.fake_l = _FakeLoader(self, False, 0, 0, 0) if version.parse(\n",
    "            fastai.__version__) >= version.parse(\"2.1\") else _FakeLoader(self, False, 0, 0)\n",
    "        if sum([len(dl.dataset) for dl in loaders]) > 0:\n",
    "            self._get_idxs()  # Do not apply on an empty dataset\n",
    "\n",
    "    def new(self, *args, **kwargs):\n",
    "        loaders = [dl.new(*args, **kwargs) for dl in self.loaders]\n",
    "        return type(self)(*loaders, path=self.path, device=self.device)\n",
    "\n",
    "#     def __len__(self): return len(self.loaders[0])\n",
    "    def __len__(self): return self.loaders[0].__len__()\n",
    "\n",
    "    def _get_vals(self, x):\n",
    "        \"Checks for duplicates in batches\"\n",
    "        idxs, new_x = [], []\n",
    "        for i, o in enumerate(x):\n",
    "            x[i] = o.cpu().numpy().flatten()\n",
    "        for idx, o in enumerate(x):\n",
    "            if not self._arrayisin(o, new_x):\n",
    "                idxs.append(idx)\n",
    "                new_x.append(o)\n",
    "        return idxs\n",
    "\n",
    "    def _get_idxs(self):\n",
    "        \"Get `x` and `y` indices for batches of data\"\n",
    "        self.n_inps = [dl.n_inp for dl in self.loaders]\n",
    "        self.x_idxs = self._split_idxs(self.n_inps)\n",
    "\n",
    "        # Identify duplicate targets\n",
    "        dl_dict = dict(zip(range(0, len(self.loaders)), self.n_inps))\n",
    "        outs = L([])\n",
    "        for key, n_inp in dl_dict.items():\n",
    "            b = next(iter(self.loaders[key]))\n",
    "            outs += L(b[n_inp:])\n",
    "        self.y_idxs = self._get_vals(outs)\n",
    "\n",
    "    def __iter__(self):\n",
    "        z = zip(*[_loaders[i.fake_l.num_workers == 0](i.fake_l) for i in self.loaders])\n",
    "        for b in z:\n",
    "            inps = []\n",
    "            outs = []\n",
    "            if self.device is not None:\n",
    "                b = to_device(b, self.device)\n",
    "            for batch, dl in zip(b, self.loaders):\n",
    "                if hasattr(dl, 'idxs'): self.idxs = dl.idxs\n",
    "                if hasattr(dl, 'input_idxs'): self.input_idxs = dl.input_idxs\n",
    "                batch = dl.after_batch(batch)\n",
    "                inps += batch[:dl.n_inp]\n",
    "                outs += batch[dl.n_inp:]\n",
    "            inps = tuple([tuple(L(inps)[idx]) if isinstance(idx, list) else inps[idx]\n",
    "                          for idx in self.x_idxs]) if len(self.x_idxs) > 1 else tuple(L(outs)[self.x_idxs][0])\n",
    "            outs = tuple(L(outs)[self.y_idxs]) if len(self.y_idxs) > 1 else L(outs)[self.y_idxs][0]\n",
    "            yield inps, outs\n",
    "\n",
    "    def one_batch(self):\n",
    "        \"Grab one batch of data\"\n",
    "        with self.fake_l.no_multiproc():\n",
    "            res = first(self)\n",
    "        if hasattr(self, 'it'):\n",
    "            delattr(self, 'it')\n",
    "        return res\n",
    "\n",
    "    def shuffle_fn(self, idxs):\n",
    "        \"Generate the same idxs for all dls in each batch when shuffled\"\n",
    "        if self.count == 0:\n",
    "            self.shuffled_idxs = np.random.permutation(idxs)\n",
    "        # sort each batch\n",
    "        for i in range(len(self.shuffled_idxs)//self.bs + 1):\n",
    "            self.shuffled_idxs[i*self.bs:(i+1)*self.bs] = np.sort(self.shuffled_idxs[i*self.bs:(i+1)*self.bs])\n",
    "        self.count += 1\n",
    "        if self.count == len(self.loaders):\n",
    "            self.count = 0\n",
    "        return self.shuffled_idxs\n",
    "\n",
    "    def show_batch(self):\n",
    "        \"Show a batch of data\"\n",
    "        for dl in self.loaders:\n",
    "            dl.show_batch()\n",
    "\n",
    "    def to(self, device): self.device = device\n",
    "\n",
    "    def _arrayisin(self, arr, arr_list):\n",
    "        \"Checks if `arr` is in `arr_list`\"\n",
    "        for a in arr_list:\n",
    "            if np.array_equal(arr, a):\n",
    "                return True\n",
    "        return False\n",
    "\n",
    "    def _split_idxs(self, a):\n",
    "        a_cum = np.array(a).cumsum().tolist()\n",
    "        b = np.arange(sum(a)).tolist()\n",
    "        start = 0\n",
    "        b_ = []\n",
    "        for i, idx in enumerate(range(len(a))):\n",
    "            end = a_cum[i]\n",
    "            b_.append(b[start:end] if end - start > 1 else b[start])\n",
    "            start = end\n",
    "        return b_\n",
    "    \n",
    "\n",
    "class MixedDataLoaders(DataLoaders):\n",
    "    pass"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "# export\n",
    "\n",
    "def get_mixed_dls(*dls, device=None, shuffle_train=None, shuffle_valid=None, **kwargs):\n",
    "    _mixed_train_dls = []\n",
    "    _mixed_valid_dls = []\n",
    "    for dl in dls:\n",
    "        _mixed_train_dls.append(dl.train)\n",
    "        _mixed_valid_dls.append(dl.valid)\n",
    "        if shuffle_train is None: shuffle_train = dl.train.shuffle\n",
    "        if shuffle_valid is None: shuffle_valid = dl.valid.shuffle\n",
    "        if device is None: device = dl.train.device\n",
    "    mixed_train_dl = MixedDataLoader(*_mixed_train_dls, shuffle=shuffle_train, **kwargs)\n",
    "    mixed_valid_dl = MixedDataLoader(*_mixed_valid_dls, shuffle=shuffle_valid, **kwargs)\n",
    "    mixed_dls = MixedDataLoaders(mixed_train_dl, mixed_valid_dl, device=device)\n",
    "    return mixed_dls"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/html": [
       "<table border=\"1\" class=\"dataframe\">\n",
       "  <thead>\n",
       "    <tr style=\"text-align: right;\">\n",
       "      <th></th>\n",
       "      <th>workclass</th>\n",
       "      <th>education</th>\n",
       "      <th>marital-status</th>\n",
       "      <th>age</th>\n",
       "      <th>fnlwgt</th>\n",
       "      <th>salary</th>\n",
       "    </tr>\n",
       "  </thead>\n",
       "  <tbody>\n",
       "    <tr>\n",
       "      <th>0</th>\n",
       "      <td>?</td>\n",
       "      <td>Some-college</td>\n",
       "      <td>Married-civ-spouse</td>\n",
       "      <td>62.999999</td>\n",
       "      <td>149697.998687</td>\n",
       "      <td>&lt;50k</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>1</th>\n",
       "      <td>Private</td>\n",
       "      <td>5th-6th</td>\n",
       "      <td>Separated</td>\n",
       "      <td>36.000000</td>\n",
       "      <td>177616.000313</td>\n",
       "      <td>&lt;50k</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>2</th>\n",
       "      <td>Local-gov</td>\n",
       "      <td>Some-college</td>\n",
       "      <td>Separated</td>\n",
       "      <td>30.000000</td>\n",
       "      <td>178383.000379</td>\n",
       "      <td>&lt;50k</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>3</th>\n",
       "      <td>Self-emp-not-inc</td>\n",
       "      <td>Some-college</td>\n",
       "      <td>Married-civ-spouse</td>\n",
       "      <td>27.000000</td>\n",
       "      <td>411950.011190</td>\n",
       "      <td>&lt;50k</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>4</th>\n",
       "      <td>Private</td>\n",
       "      <td>Bachelors</td>\n",
       "      <td>Married-civ-spouse</td>\n",
       "      <td>37.000000</td>\n",
       "      <td>192938.999932</td>\n",
       "      <td>&gt;=50k</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>5</th>\n",
       "      <td>Private</td>\n",
       "      <td>Masters</td>\n",
       "      <td>Divorced</td>\n",
       "      <td>54.000000</td>\n",
       "      <td>161691.000074</td>\n",
       "      <td>&gt;=50k</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>6</th>\n",
       "      <td>Private</td>\n",
       "      <td>HS-grad</td>\n",
       "      <td>Married-civ-spouse</td>\n",
       "      <td>36.000000</td>\n",
       "      <td>95336.001179</td>\n",
       "      <td>&gt;=50k</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>7</th>\n",
       "      <td>State-gov</td>\n",
       "      <td>HS-grad</td>\n",
       "      <td>Married-civ-spouse</td>\n",
       "      <td>46.000000</td>\n",
       "      <td>273770.997233</td>\n",
       "      <td>&lt;50k</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>8</th>\n",
       "      <td>Self-emp-not-inc</td>\n",
       "      <td>HS-grad</td>\n",
       "      <td>Married-civ-spouse</td>\n",
       "      <td>68.000001</td>\n",
       "      <td>197015.000115</td>\n",
       "      <td>&lt;50k</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>9</th>\n",
       "      <td>Self-emp-not-inc</td>\n",
       "      <td>Some-college</td>\n",
       "      <td>Married-civ-spouse</td>\n",
       "      <td>28.000000</td>\n",
       "      <td>149323.999684</td>\n",
       "      <td>&lt;50k</td>\n",
       "    </tr>\n",
       "  </tbody>\n",
       "</table>"
      ],
      "text/plain": [
       "<IPython.core.display.HTML object>"
      ]
     },
     "metadata": {},
     "output_type": "display_data"
    },
    {
     "data": {
      "text/html": [
       "<table border=\"1\" class=\"dataframe\">\n",
       "  <thead>\n",
       "    <tr style=\"text-align: right;\">\n",
       "      <th></th>\n",
       "      <th>education-num_na</th>\n",
       "      <th>education-num</th>\n",
       "      <th>salary</th>\n",
       "    </tr>\n",
       "  </thead>\n",
       "  <tbody>\n",
       "    <tr>\n",
       "      <th>0</th>\n",
       "      <td>False</td>\n",
       "      <td>10.0</td>\n",
       "      <td>&lt;50k</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>1</th>\n",
       "      <td>False</td>\n",
       "      <td>9.0</td>\n",
       "      <td>&lt;50k</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>2</th>\n",
       "      <td>False</td>\n",
       "      <td>9.0</td>\n",
       "      <td>&gt;=50k</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>3</th>\n",
       "      <td>False</td>\n",
       "      <td>10.0</td>\n",
       "      <td>&lt;50k</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>4</th>\n",
       "      <td>False</td>\n",
       "      <td>13.0</td>\n",
       "      <td>&gt;=50k</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>5</th>\n",
       "      <td>False</td>\n",
       "      <td>13.0</td>\n",
       "      <td>&lt;50k</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>6</th>\n",
       "      <td>False</td>\n",
       "      <td>10.0</td>\n",
       "      <td>&lt;50k</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>7</th>\n",
       "      <td>False</td>\n",
       "      <td>11.0</td>\n",
       "      <td>&lt;50k</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>8</th>\n",
       "      <td>False</td>\n",
       "      <td>12.0</td>\n",
       "      <td>&gt;=50k</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>9</th>\n",
       "      <td>False</td>\n",
       "      <td>10.0</td>\n",
       "      <td>&lt;50k</td>\n",
       "    </tr>\n",
       "  </tbody>\n",
       "</table>"
      ],
      "text/plain": [
       "<IPython.core.display.HTML object>"
      ]
     },
     "metadata": {},
     "output_type": "display_data"
    }
   ],
   "source": [
    "from tsai.data.tabular import *\n",
    "\n",
    "path = untar_data(URLs.ADULT_SAMPLE)\n",
    "df = pd.read_csv(path/'adult.csv')\n",
    "# df['salary'] = np.random.rand(len(df)) # uncomment to simulate a cont dependent variable\n",
    "target = 'salary'\n",
    "splits = RandomSplitter()(range_of(df))\n",
    "\n",
    "cat_names = ['workclass', 'education', 'marital-status']\n",
    "cont_names = ['age', 'fnlwgt']\n",
    "dls1 = get_tabular_dls(df, cat_names=cat_names, cont_names=cont_names, y_names=target, splits=splits, bs=512)\n",
    "dls1.show_batch()\n",
    "\n",
    "cat_names = None #['occupation', 'relationship', 'race']\n",
    "cont_names = ['education-num']\n",
    "dls2 = get_tabular_dls(df, cat_names=cat_names, cont_names=cont_names, y_names=target, splits=splits, bs=128)\n",
    "dls2.show_batch()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/html": [
       "<table border=\"1\" class=\"dataframe\">\n",
       "  <thead>\n",
       "    <tr style=\"text-align: right;\">\n",
       "      <th></th>\n",
       "      <th>workclass</th>\n",
       "      <th>education</th>\n",
       "      <th>marital-status</th>\n",
       "      <th>age</th>\n",
       "      <th>fnlwgt</th>\n",
       "      <th>salary</th>\n",
       "    </tr>\n",
       "  </thead>\n",
       "  <tbody>\n",
       "    <tr>\n",
       "      <th>0</th>\n",
       "      <td>Self-emp-not-inc</td>\n",
       "      <td>HS-grad</td>\n",
       "      <td>Never-married</td>\n",
       "      <td>19.000000</td>\n",
       "      <td>137577.998451</td>\n",
       "      <td>&lt;50k</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>1</th>\n",
       "      <td>Private</td>\n",
       "      <td>HS-grad</td>\n",
       "      <td>Never-married</td>\n",
       "      <td>23.000001</td>\n",
       "      <td>199884.000276</td>\n",
       "      <td>&lt;50k</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>2</th>\n",
       "      <td>Self-emp-not-inc</td>\n",
       "      <td>Prof-school</td>\n",
       "      <td>Married-civ-spouse</td>\n",
       "      <td>52.999999</td>\n",
       "      <td>33303.999880</td>\n",
       "      <td>&gt;=50k</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>3</th>\n",
       "      <td>Private</td>\n",
       "      <td>10th</td>\n",
       "      <td>Never-married</td>\n",
       "      <td>28.000000</td>\n",
       "      <td>204516.000215</td>\n",
       "      <td>&lt;50k</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>4</th>\n",
       "      <td>Private</td>\n",
       "      <td>10th</td>\n",
       "      <td>Never-married</td>\n",
       "      <td>28.000000</td>\n",
       "      <td>412148.999546</td>\n",
       "      <td>&lt;50k</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>5</th>\n",
       "      <td>Self-emp-not-inc</td>\n",
       "      <td>Bachelors</td>\n",
       "      <td>Married-civ-spouse</td>\n",
       "      <td>57.999999</td>\n",
       "      <td>310013.997374</td>\n",
       "      <td>&lt;50k</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>6</th>\n",
       "      <td>State-gov</td>\n",
       "      <td>HS-grad</td>\n",
       "      <td>Never-married</td>\n",
       "      <td>35.000000</td>\n",
       "      <td>237873.000453</td>\n",
       "      <td>&lt;50k</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>7</th>\n",
       "      <td>Private</td>\n",
       "      <td>Bachelors</td>\n",
       "      <td>Married-civ-spouse</td>\n",
       "      <td>37.000000</td>\n",
       "      <td>178948.000389</td>\n",
       "      <td>&gt;=50k</td>\n",
       "    </tr>\n",
       "  </tbody>\n",
       "</table>"
      ],
      "text/plain": [
       "<IPython.core.display.HTML object>"
      ]
     },
     "metadata": {},
     "output_type": "display_data"
    },
    {
     "data": {
      "text/html": [
       "<table border=\"1\" class=\"dataframe\">\n",
       "  <thead>\n",
       "    <tr style=\"text-align: right;\">\n",
       "      <th></th>\n",
       "      <th>education-num_na</th>\n",
       "      <th>education-num</th>\n",
       "      <th>salary</th>\n",
       "    </tr>\n",
       "  </thead>\n",
       "  <tbody>\n",
       "    <tr>\n",
       "      <th>0</th>\n",
       "      <td>False</td>\n",
       "      <td>9.0</td>\n",
       "      <td>&lt;50k</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>1</th>\n",
       "      <td>False</td>\n",
       "      <td>9.0</td>\n",
       "      <td>&lt;50k</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>2</th>\n",
       "      <td>False</td>\n",
       "      <td>15.0</td>\n",
       "      <td>&gt;=50k</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>3</th>\n",
       "      <td>False</td>\n",
       "      <td>6.0</td>\n",
       "      <td>&lt;50k</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>4</th>\n",
       "      <td>False</td>\n",
       "      <td>6.0</td>\n",
       "      <td>&lt;50k</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>5</th>\n",
       "      <td>False</td>\n",
       "      <td>13.0</td>\n",
       "      <td>&lt;50k</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>6</th>\n",
       "      <td>False</td>\n",
       "      <td>9.0</td>\n",
       "      <td>&lt;50k</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>7</th>\n",
       "      <td>False</td>\n",
       "      <td>13.0</td>\n",
       "      <td>&gt;=50k</td>\n",
       "    </tr>\n",
       "  </tbody>\n",
       "</table>"
      ],
      "text/plain": [
       "<IPython.core.display.HTML object>"
      ]
     },
     "metadata": {},
     "output_type": "display_data"
    }
   ],
   "source": [
    "dls = get_mixed_dls(dls1, dls2, bs=8)\n",
    "first(dls.train)\n",
    "first(dls.valid)\n",
    "torch.save(dls,'export/mixed_dls.pth')\n",
    "del dls\n",
    "dls = torch.load('export/mixed_dls.pth')\n",
    "dls.train.show_batch()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "((tensor([[ 7, 12,  5],\n",
       "          [ 5, 12,  5],\n",
       "          [ 7, 15,  3],\n",
       "          [ 5,  1,  5],\n",
       "          [ 5,  1,  5],\n",
       "          [ 7, 10,  3],\n",
       "          [ 8, 12,  5],\n",
       "          [ 5, 10,  3]]),\n",
       "  tensor([[-1.4394, -0.4971],\n",
       "          [-1.1456,  0.0957],\n",
       "          [ 1.0581, -1.4893],\n",
       "          [-0.7783,  0.1397],\n",
       "          [-0.7783,  2.1153],\n",
       "          [ 1.4254,  1.1435],\n",
       "          [-0.2641,  0.4571],\n",
       "          [-0.1172, -0.1035]])),\n",
       " (tensor([[1],\n",
       "          [1],\n",
       "          [1],\n",
       "          [1],\n",
       "          [1],\n",
       "          [1],\n",
       "          [1],\n",
       "          [1]]),\n",
       "  tensor([[-0.4232],\n",
       "          [-0.4232],\n",
       "          [ 1.9228],\n",
       "          [-1.5961],\n",
       "          [-1.5961],\n",
       "          [ 1.1408],\n",
       "          [-0.4232],\n",
       "          [ 1.1408]])))"
      ]
     },
     "execution_count": null,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "xb, yb = first(dls.train)\n",
    "xb"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "(torch.Size([8, 3]),\n",
       " torch.Size([8, 2]),\n",
       " torch.Size([8, 1]),\n",
       " torch.Size([8, 1]))"
      ]
     },
     "execution_count": null,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "xs, ys = first(dls.train)\n",
    "xs[0][0].shape, xs[0][1].shape, xs[1][0].shape, xs[1][1].shape"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "(TSTensor(samples:8, vars:2, len:5, device=cpu),\n",
       " tensor([0., 1., 2., 3., 4., 5., 6., 7.]))"
      ]
     },
     "execution_count": null,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "from tsai.data.validation import TimeSplitter\n",
    "from tsai.data.core import TSRegression, get_ts_dls\n",
    "X = np.repeat(np.repeat(np.arange(8)[:, None, None], 2, 1), 5, 2).astype(float)\n",
    "X = np.concatenate([X, X])\n",
    "y = np.concatenate([np.arange(len(X)//2)]*2)\n",
    "alphabet = np.array(list(string.ascii_lowercase))\n",
    "# y = alphabet[y]\n",
    "splits = TimeSplitter(.5, show_plot=False)(range_of(X))\n",
    "tfms = [None, TSRegression()]\n",
    "dls1 = get_ts_dls(X, y, splits=splits, tfms=tfms)\n",
    "dls1.one_batch()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "(tensor([[7, 7],\n",
       "         [1, 1],\n",
       "         [8, 8],\n",
       "         [6, 6],\n",
       "         [4, 4],\n",
       "         [2, 2],\n",
       "         [5, 5],\n",
       "         [3, 3]]),\n",
       " tensor([[600.],\n",
       "         [  0.],\n",
       "         [700.],\n",
       "         [500.],\n",
       "         [300.],\n",
       "         [100.],\n",
       "         [400.],\n",
       "         [200.]]),\n",
       " tensor([[6],\n",
       "         [0],\n",
       "         [7],\n",
       "         [5],\n",
       "         [3],\n",
       "         [1],\n",
       "         [4],\n",
       "         [2]], dtype=torch.int8))"
      ]
     },
     "execution_count": null,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "data = np.concatenate([np.repeat(np.arange(8)[:, None], 3, 1)*np.array([1, 10, 100])]*2)\n",
    "df = pd.DataFrame(data, columns=['cat1', 'cat2', 'cont'])\n",
    "df['cont'] = df['cont'].astype(float)\n",
    "df['target'] = y\n",
    "cat_names = ['cat1', 'cat2']\n",
    "cont_names = ['cont']\n",
    "target = 'target'\n",
    "dls2 = get_tabular_dls(df, procs=[Categorify, FillMissing, #Normalize\n",
    "                                 ], cat_names=cat_names, cont_names=cont_names, y_names=target, splits=splits, bs=8)\n",
    "dls2.one_batch()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "((TSTensor(samples:8, vars:2, len:5, device=cpu), tensor([0., 1., 2., 3., 4., 5., 6., 7.])),)\n"
     ]
    }
   ],
   "source": [
    "z = zip(_loaders[dls1.train.fake_l.num_workers == 0](dls1.train.fake_l))\n",
    "for b in z: \n",
    "    print(b)\n",
    "    break"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "bs = 8\n",
    "dls = get_mixed_dls(dls1, dls2, bs=bs)\n",
    "dl = dls.train\n",
    "xb, yb = dl.one_batch()\n",
    "test_eq(len(xb), 2)\n",
    "test_eq(len(xb[0]), bs)\n",
    "test_eq(len(xb[1]), 2)\n",
    "test_eq(len(xb[1][0]), bs)\n",
    "test_eq(len(xb[1][1]), bs)\n",
    "test_eq(xb[0].data[:, 0, 0].long(), xb[1][0][:, 0] - 1) # categorical data and ts are in synch\n",
    "test_eq(xb[0].data[:, 0, 0], (xb[1][1]/100).flatten()) # continuous data and ts are in synch\n",
    "test_eq(tensor(dl.input_idxs), yb.long().cpu())\n",
    "dl = dls.valid\n",
    "xb, yb = dl.one_batch()\n",
    "test_eq(tensor(y[dl.input_idxs]), yb.long().cpu())"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "#hide\n",
    "from tsai.imports import create_scripts\n",
    "from tsai.export import get_nb_name\n",
    "nb_name = get_nb_name()\n",
    "create_scripts(nb_name);"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": []
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 4
}
